package etnorservice.etnor_service.service;




import etnorservice.etnor_service.domain.GitAuthConfig;
import etnorservice.etnor_service.utils.GitUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.eclipse.jgit.api.Git;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

@Slf4j
@Service
public class GitService {

    public List<String> getBranches(String repoUrl, GitAuthConfig auth) {
        try {
            return GitUtils.listBranches(repoUrl, auth);
        } catch (Exception e) {
            log.error("获取分支失败: {}", repoUrl, e);
            throw new RuntimeException("获取分支失败: " + e.getMessage());
        }
    }

    public void testConnection(String repoUrl, GitAuthConfig auth) {
        try {
            GitUtils.listBranches(repoUrl, auth);
        } catch (Exception e) {
            log.error("测试连接失败: {}", repoUrl, e);
            throw new RuntimeException("仓库连接失败: " + e.getMessage());
        }
    }

    public void cloneOrPull(String repoUrl, String branch, String targetPath, GitAuthConfig auth) {
        try {
            var targetDir = new File(targetPath);
            if (targetDir.exists() && new File(targetPath + "/.git").exists()) {
                // 已存在仓库，执行pull
                log.info("更新已存在的仓库: {}", repoUrl);
                try (var git = Git.open(targetDir)) {
                    // fetch with auth
                    var fetchCommand = git.fetch();
                    GitUtils.configureAuth(fetchCommand, auth);
                    fetchCommand.call();

                    // checkout
                    git.checkout().setName(branch).call();

                    // pull with auth
                    var pullCommand = git.pull();
                    GitUtils.configureAuth(pullCommand, auth);
                    pullCommand.call();
                }
            } else {
                // 不存在仓库，执行clone
                log.info("克隆新仓库: {}", repoUrl);
                GitUtils.cloneRepository(repoUrl, branch, targetPath, auth);
            }
        } catch (Exception e) {
            log.error("克隆/更新仓库失败: {}, 错误: {}", repoUrl, e.getMessage());
            throw new RuntimeException("代码更新失败: " + e.getMessage());
        }
    }

}